package com.qf.realm;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.SysUsers;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.realm
 * @Description:
 * @Date 2022/10/10 17:10
 * 加载用户和权限信息
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;

//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> roles = roleService.findRoleById(user.getId());

//        角色 的set集合
        authorizationInfo.setRoles(roles);

        Set<String> menu = menuService.findMenuById(user.getId());
//        权限 的set集合
        authorizationInfo.setStringPermissions(menu);

        return authorizationInfo;
    }


//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String useruame = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        if (StringUtils.isEmpty(useruame) || StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码为空");
        }

        SysUsers user = userService.findByUsername(useruame);
        if (user==null){
            throw new UnknownAccountException("用户不存在");
        }
        if (user.getStatus() == 0){
            throw new LockedAccountException("账户已锁定");
        }

        if (!user.getPassword().equalsIgnoreCase(password)){
            throw new CredentialsException("密码错误");
        }


//        主要的
//        密码
//        真实姓名
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),user.getRealname());

        return authenticationInfo;
    }
}
